<template>
  <div>
    <layout-box one="权限管理" two="角色列表">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border swiper>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- el-row表示一行，el-col表示一列 -->
            <el-row
              :class="['bdbottom',i1==0?'bdtop':'','vcenter']"
              :key="item1.id"
              v-for="(item1,i1) in scope.row.children"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag type="primary" closable @close="removeRightById(scope.row,item1.id)">
                  {{item1.authName}}
                  <i class="el-icon-caret-right"></i>
                </el-tag>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环 嵌套渲染二级权限 -->
                <el-row
                  :class="[i2==0?'':'bdtop','vcenter']"
                  :key="item2.id"
                  v-for="(item2,i2) in item1.children"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                      {{item2.authName}}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                      :key="item3.id"
                      v-for="item3 in item2.children"
                      type="warning"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-primary">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRight(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </layout-box>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%" @close="resetDefKeys">
      <!-- 树形控件 -->
      <!-- data：数据来源 props：怎么显示数据 default-expand-all默认展开所有节点 node-key是树节点的唯一标识 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 所有权限数据
      rightslist: [],
      rightsDialogVisible: false,
      treeProps: {
        // label和children的属性名是固定的，后面赋的值是数据源上的属性
        children: "children",
        label: "authName"
      },
      // 默认选中的树节点id值数组
      defKeys: [],
      // 用于记录角色id
      roleId: 0
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      // console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取角色列表失败");
      this.rolelist = res.data;
      // console.log(this.rolelist);
    },
    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹出框提示
      const confirmResult = await this.$confirm(
        "此操作将永久删除该权限，是否继续？",
        "提示",
        {
          confirmButtomText: "确定",
          cancelButtomText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult == "cancel") {
        // if (confirmResult != "confirm") {
        return this.$message.info("取消了删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status != 200) {
        return this.$message.error("删除权限失败");
      }
      this.$message.success("删除权限成功");
      // this.getRolesList // 整个列表页面刷新
      // 把服务器返回的该角色下全新的权限赋值给整个角色的children属性
      role.children = res.data;
    },
    // 分配权限
    async showSetRight(role) {
      this.roleId = role.id; // 保存role id
      this.rightsDialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200) {
        return this.$message.error("加载权限列表失败");
      }
      this.rightslist = res.data;
      this.getDefDkeys(role, this.defKeys);
    },
    // 通过递归的形式获取角色下所有三级权限的id，并保存到defKeys中
    // 获取角色下的三级权限(角色对象，数组)
    getDefDkeys(node, arr) {
      // 如果当前node节点不包含children属性，则是三级节点
      if (!node.children) {
        // 递归最重要的是结束条件
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getDefDkeys(item, arr);
      });
    },
    // 监听分配权限对话框 关闭对话框时重置defKeys
    resetDefKeys() {
      this.defKeys = [];
    },
    // 为角色分配权限 ...是展开运算符
    async allotRights() {
      // 获取所有全选与半选的节点值(即复选框内的值=>权限id)
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status != 200) {
        return this.$message.error("修改权限失败");
      }
      this.$message.success("修改权限成功");
      this.getRolesList() // 重新获取角色列表数据
      this.rightsDialogVisible = false; // 关闭弹窗
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex; // 弹性布局
  align-items: center;
}
</style>